package com.yunchao.feature.lock.presentation.screen

import android.os.Bundle
import androidx.annotation.LayoutRes
import androidx.lifecycle.lifecycleScope
import com.yunchao.feature.base.presentation.activity.BaseKeyEventFragment
import com.yunchao.feature.lock.domain.model.LockInfoModel
import com.yunchao.feature.base.presentation.ext.hideLoadingDialog
import com.yunchao.feature.base.presentation.ext.showLoadingDialog
import com.yunchao.feature.base.presentation.ext.toast
import com.yunchao.library.lock.LockEPCInfo
import kotlinx.coroutines.launch
import org.koin.androidx.viewmodel.ext.android.viewModel
import timber.log.Timber

internal abstract class LockFragment(@LayoutRes contentLayoutId: Int) :
    BaseKeyEventFragment(contentLayoutId) {

    protected val viewModel: LockViewModel by viewModel<LockViewModel>()

    protected var lockEPCInfo: LockEPCInfo? = null

    override fun initData(savedInstanceState: Bundle?) {
        lifecycleScope.launch { viewModel.uiStateFlow.collect(::render) }
        lifecycleScope.launch { viewModel.uiEffectFlow.collect(::sideEffect) }
    }

    private fun render(state: LockViewModel.UiState) {
        when (state) {
            is LockViewModel.UiState.Idle -> handlePageIdle()
            is LockViewModel.UiState.Success -> handlePageSuccess(state.lockInfoModel)
        }
    }

    private fun sideEffect(effect: LockViewModel.UiEffect) {
        when (effect) {
            is LockViewModel.UiEffect.ShowToast -> toast(effect.msg)
            is LockViewModel.UiEffect.ShowLoading -> showLoadingDialog()
            is LockViewModel.UiEffect.HideLoading -> hideLoadingDialog()
        }
    }


    open fun handlePageSuccess(lockInfoModel: LockInfoModel) {
        Timber.d("handlePageSuccess: $lockInfoModel")
        this.lockEPCInfo = lockInfoModel.lockEPCInfo
    }

    abstract fun handlePageIdle()

    override fun onceScanLock() {
        super.onceScanLock()
        viewModel.inventoryOnce()
    }
}